//
//  PersonMessageViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/10/25.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "PersonMessageViewController.h"
#import "PersonMessageTableViewCell.h"
#import "PersonMessageModel.h"

#define TEXTVIEWMESSAGE @"请输入~"

#define postMsgList @"postMsgList"
#define setMsgInfo @"setMsgInfo"
#define getMessageRecordList @"getMessageRecordList"
#define MESSAGE_WIDTH IPHONE_WIDTH-56-30

@interface PersonMessageViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UIGestureRecognizerDelegate>
{
    UITableView *_tableView;//列表
    PersonMessageModel *_model;//消息model
    UIView *_backMsgView;//消息textView的父视图
    UITextView *_msgTextView;//消息textView
    UITapGestureRecognizer *_tapGesture;//手势
}
@property (nonatomic,assign) NSInteger deleteRow;
@property (nonatomic,strong) UIView *deleteView;//删除view
@end

@implementation PersonMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftBackNavigation];
    [self setRightBackNavigation];
    [self setNavigationTitle:@"消息查看"];
    [self creatView];
    [self creatTextView];
    [self messageListRequest];
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
   // [self sendMessageWithText:@"asfasgasg"];
    //[self messageListRequest];
    // Do any additional setup after loading the view.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    /*
     iphone 6:
     中文
     2014-12-31 11:16:23.643 Demo[686:41289] 键盘高度是  258
     2014-12-31 11:16:23.644 Demo[686:41289] 键盘宽度是  375
     英文
     2014-12-31 11:55:21.417 Demo[1102:58972] 键盘高度是  216
     2014-12-31 11:55:21.417 Demo[1102:58972] 键盘宽度是  375
     
     iphone  6 plus：
     英文：
     2014-12-31 11:31:14.669 Demo[928:50593] 键盘高度是  226
     2014-12-31 11:31:14.669 Demo[928:50593] 键盘宽度是  414
     中文：
     2015-01-07 09:22:49.438 Demo[622:14908] 键盘高度是  271
     2015-01-07 09:22:49.439 Demo[622:14908] 键盘宽度是  414
     
     iphone 5 :
     2014-12-31 11:19:36.452 Demo[755:43233] 键盘高度是  216
     2014-12-31 11:19:36.452 Demo[755:43233] 键盘宽度是  320
     
     ipad Air：
     2014-12-31 11:28:32.178 Demo[851:48085] 键盘高度是  264
     2014-12-31 11:28:32.178 Demo[851:48085] 键盘宽度是  768
     
     ipad2 ：
     2014-12-31 11:33:57.258 Demo[1014:53043] 键盘高度是  264
     2014-12-31 11:33:57.258 Demo[1014:53043] 键盘宽度是  768
     */
    
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        _backMsgView.y=IPHONE_HEIGHT-51-height-64;
    }];
    _tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClick)];
    
    [_tableView addGestureRecognizer:_tapGesture];
    _tableView.y-=height;
    
    // CGFloat width = keyboardRect.size.width;
    
}

- (void)tapGestureClick{
    [_msgTextView resignFirstResponder];
}

//#pragma mark -滚动视图delegate
//
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (_msgTextView.superview iski) {
//        <#statements#>
//    }
//}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
//    //获取键盘高度
//    NSDictionary *userInfo = [aNotification userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [aValue CGRectValue];
//    CGFloat height = keyboardRect.size.height;

    [UIView animateWithDuration:0.3 animations:^{
        _backMsgView.y=IPHONE_HEIGHT-51-64;
    }];
    [_tableView removeGestureRecognizer:_tapGesture];
    _tableView.y=0;
    
}

#pragma mark - creatTableView
- (void)creatView{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-64-60) style:UITableViewStylePlain];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    [self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_tableView];
    
    //    self.definesPresentationContext = YES;
}

#pragma mark -creatTextView
- (void)creatTextView{
    self.automaticallyAdjustsScrollViewInsets=NO;
    _backMsgView=[[UIView alloc]initWithFrame:CGRectMake(0, IPHONE_HEIGHT-51-64, IPHONE_WIDTH, 51)];
    _backMsgView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_backMsgView];
    
    UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 1)];
    line.backgroundColor=BACKCOLOR_GRAY;
    [_backMsgView addSubview:line];
    //消息框
    _msgTextView=[[UITextView alloc]initWithFrame:CGRectMake(8, 8, IPHONE_WIDTH-76-8, 35)];
    _msgTextView.layer.borderWidth=1;
    _msgTextView.layer.borderColor=[BACKCOLOR_GRAY CGColor];
    _msgTextView.delegate=self;
    _msgTextView.font=FONT_15;
    _msgTextView.text=TEXTVIEWMESSAGE;
    _msgTextView.textColor=[UIColor lightGrayColor];
    [_backMsgView addSubview:_msgTextView];
    
    //发送按钮
    UIButton *sendButton=[MyControl creatButtonWithFrame:CGRectMake(_msgTextView.x+_msgTextView.width+8, 8, 60, _msgTextView.height) target:self sel:@selector(sendButtonClick) tag:300 image:nil title:@"发送"];
    [sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sendButton.backgroundColor=COLOR_MIDGREEN;
    sendButton.layer.masksToBounds=YES;
    sendButton.layer.cornerRadius=5;
    [_backMsgView addSubview:sendButton];
}

#pragma mark -删除的view
- (void)creatViewDeleteView{
    if (_deleteView) {
        return;
    }
    _deleteView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    _deleteView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_deleteView];

    
    UIView *alphaView=[[UIView alloc]initWithFrame:CGRectMake(0,0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    alphaView.alpha=0.4;
    alphaView.backgroundColor=[UIColor blackColor];
    [_deleteView addSubview:alphaView];
    
    //点击手势
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TwoTapGestureRecognizer)];
    tapGesture.delegate=self;
    [tapGesture setNumberOfTapsRequired:1];
    [tapGesture setNumberOfTouchesRequired:1];
    [alphaView addGestureRecognizer:tapGesture];
    
    //删除按钮
    UIButton *button=[MyControl creatButtonWithFrame:CGRectMake(20, (IPHONE_HEIGHT-50-64)/2, IPHONE_WIDTH-40, 50) target:self sel:@selector(deleteButtonClick) tag:0 image:nil title:@"删除"];
    button.backgroundColor=[UIColor whiteColor];
    [_deleteView addSubview:button];
}

#pragma mark -删除事件
- (void)deleteButtonClick{
    [self setDeleteMessageInfoRequest];
}

#pragma mark -手势响应
- (void)TwoTapGestureRecognizer{
    if (self.deleteView) {
        [self.deleteView removeFromSuperview];
        self.deleteView=nil;
    }
}

- (void)sendButtonClick{
    if ([_msgTextView.text isEqualToString:TEXTVIEWMESSAGE]||_msgTextView.text.length==0) {
        [LZXHelper postMessageWithText:@"请输入发送内容!" View:IPHONEWINDOW];
        return;
    }
    //非空判断
    if ([LZXHelper isEmpty:_msgTextView.text]) {
        [LZXHelper postMessageWithText:@"发送内容不能为空!" View:IPHONEWINDOW];
        return;
    }
    [_msgTextView resignFirstResponder];
    [self sendMessageWithText:_msgTextView.text];
}

#pragma mark -textViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:TEXTVIEWMESSAGE]) {
        textView.textColor=[UIColor blackColor];
        textView.text=@"";
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    if (textView.text.length==0) {
        textView.textColor=[UIColor lightGrayColor];
        textView.text=TEXTVIEWMESSAGE;
    }
    return YES;
}

//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [_msgTextView resignFirstResponder];
//}

#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_model) {
        return _model.dataArr.count;
    }
    return 0;
   //return _newsListModel.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID=@"PersonMessageTableViewCell";
    __weak PersonMessageViewController *mySelf=self;
    PersonMessageTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell=[[PersonMessageTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
//        UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 77, IPHONE_WIDTH, 1)];
//        line.backgroundColor=BACKCOLOR_GRAY;
//        [cell.contentView addSubview:line];
        cell.myBlock=^(NSInteger row){
            mySelf.deleteRow=row;
            [mySelf creatViewDeleteView];
        };
    }
        PersonMessageModel *model=_model.dataArr[indexPath.row];
    //计算内容的宽和高
    CGFloat messageWidth=[LZXHelper textWidthFromTextString:model.msgContent?model.msgContent:@"" Height:20 fontSize:13]+5;
    CGFloat messageHeight=[LZXHelper textHeightFromTextString:model.msgContent?model.msgContent:@"" width:MESSAGE_WIDTH fontSize:13]+5;
    //重置控件的布局
    if (messageWidth+16<150) {
        cell.leftMessageLabel.width=messageWidth;
        cell.leftBackView.width=150;
    }else if(messageWidth>MESSAGE_WIDTH){
        cell.leftMessageLabel.width=MESSAGE_WIDTH;
        cell.leftBackView.width=MESSAGE_WIDTH+16;
    }else{
        cell.leftMessageLabel.width=messageWidth;
        cell.leftBackView.width=messageWidth+16;
    }
    //        if (messageHeight>20) {
    cell.leftMessageLabel.height=messageHeight;
    if (![model.sendEmpId isEqual:[LZXHelper getSessionID]]) {
        cell.leftTimeLabel.textAlignment=NSTextAlignmentLeft;
        cell.leftHeadImageView.hidden=NO;
        cell.leftNameLabel.hidden=NO;
        cell.rightHeadImageView.hidden=YES;
        cell.rightNameLabel.hidden=YES;
        [cell.leftHeadImageView setImageWithURL:[NSURL URLWithString:_model.empIcon] placeholderImage:[UIImage imageNamed:@"k_portrait@2x"]];
        cell.leftNameLabel.text=model.sendEmpName?model.sendEmpName:@"";
        if (model.sendEmpId.integerValue==1) {
            cell.leftNameLabel.text=@"管理员";
        }
        cell.leftMessageLabel.text=model.msgContent?model.msgContent:@"";
        cell.leftMessageLabel.textAlignment=NSTextAlignmentLeft;
        cell.leftTimeLabel.text=model.createTime?model.createTime:@"";
        cell.leftBackView.backgroundColor=COLOR_BACKGROUND_GRAY;
//        //计算内容的宽和高
//        CGFloat messageWidth=[LZXHelper textWidthFromTextString:model.msgContent?model.msgContent:@"" Height:20 fontSize:13]+5;
//        CGFloat messageHeight=[LZXHelper textHeightFromTextString:model.msgContent?model.msgContent:@"" width:MESSAGE_WIDTH fontSize:13]+5;
//        //重置控件的布局
//        if (messageWidth+16<150) {
//            cell.leftMessageLabel.width=messageWidth;
//            cell.leftBackView.width=150;
//        }else if(messageWidth>MESSAGE_WIDTH){
//            cell.leftMessageLabel.width=MESSAGE_WIDTH;
//            cell.leftBackView.width=MESSAGE_WIDTH+16;
//        }else{
//            cell.leftMessageLabel.width=messageWidth;
//            cell.leftBackView.width=messageWidth+16;
//        }
//        if (messageHeight>20) {
//            cell.leftMessageLabel.height=messageHeight;
//        }else{
//            cell.leftMessageLabel.height=20;
//        }
        cell.leftBackView.height=cell.leftMessageLabel.height+36;
        cell.leftTimeLabel.y=cell.leftMessageLabel.y+cell.leftMessageLabel.height;
    }else{
        cell.leftTimeLabel.textAlignment=NSTextAlignmentRight;
        [cell.rightHeadImageView setImageWithURL:[NSURL URLWithString:_model.selfIcon] placeholderImage:[UIImage imageNamed:@"k_portrait@2x"]];
        cell.rightNameLabel.text=model.sendEmpName?model.sendEmpName:@"";
        cell.leftHeadImageView.hidden=YES;
        cell.leftNameLabel.hidden=YES;
        cell.rightHeadImageView.hidden=NO;
        cell.rightNameLabel.hidden=NO;
        cell.leftNameLabel.text=model.reciveEmpName?model.reciveEmpName:@"";
        cell.leftMessageLabel.text=model.msgContent?model.msgContent:@"";
        cell.leftMessageLabel.textAlignment=NSTextAlignmentRight;
        cell.leftTimeLabel.text=model.createTime?model.createTime:@"";
        cell.leftBackView.backgroundColor=COLOR_HIGHGREEN;
        if (model.reciveEmpId.integerValue==1) {
            cell.rightNameLabel.text=@"管理员";
        }
        //        }else{
//            cell.leftMessageLabel.height=20;
//        }
        cell.leftBackView.height=cell.leftMessageLabel.height+36;
        cell.leftTimeLabel.width=cell.leftBackView.width-16;
        cell.leftTimeLabel.y=cell.leftMessageLabel.y+cell.leftMessageLabel.height;
        cell.leftBackView.x=IPHONE_WIDTH-(cell.rightHeadImageView.width+8+8)-cell.leftBackView.width;
    }
        return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //计算内容的宽和高
    PersonMessageModel *model=_model.dataArr[indexPath.row];
    CGFloat messageHeight=[LZXHelper textHeightFromTextString:model.msgContent?model.msgContent:@"" width:MESSAGE_WIDTH fontSize:13]+5;
//    if (messageHeight+44>72) {
        return messageHeight+44;
//    }else{
//        return 72;
//    }
}

#pragma mark -发送消息请求

- (void)sendMessageWithText:(NSString *)message{
    NSString *msgTilte=nil;
    if (message.length<=5) {
        msgTilte=[message copy];
    }else{
        msgTilte=[message substringToIndex:5];
    }
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    NSDictionary *dict=@{
                         @"alertLevel":@"",
                         @"eventId":@"",
                         @"eventType":@"",
                         @"isReMsg":@"",
                         @"leaveTypePK":@"",
                         @"msgContent":message,
                         @"parendMsgId":@"",
                         @"msgTitle":msgTilte,
                         @"receEmpId":_receEmpId,
                         @"receEmpName":_receEmpName,
                         @"sendEmpId":[LZXHelper getSessionID],
                         @"sendEmpName":[LZXHelper getUserName],
                         };
    //将字典保存到数组中
    NSMutableArray *msgArr=[NSMutableArray new];
    [msgArr addObject:dict];
    NSMutableDictionary *msgList=[NSMutableDictionary new];
    [msgList setObject:msgArr forKey:@"msgList"];
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:msgList options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:postMsgList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
       BasicModel *model=[[BasicModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"220"]) {
            [LZXHelper postMessageWithText:model.msg View:IPHONEWINDOW];
            _msgTextView.textColor=[UIColor lightGrayColor];
            _msgTextView.text=TEXTVIEWMESSAGE;
            [self messageListRequest];
            //[_tableView reloadData];
        }else if([model.code isEqualToString:@"200"]){
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}

#pragma mark -消息列表请求

- (void)messageListRequest{
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    NSDictionary *dict=@{
                         @"fid":_pageNum,
                         @"sendEmpId":_receEmpId,
                         @"state":@"0"
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getMessageRecordList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        _model=[[PersonMessageModel alloc]initWithResponse:responseObject];
        if ([_model.code isEqualToString:@"200"]) {
            if (_isRefresh) {
                [self endRefreshWithTableView:_tableView];
            }
            [_tableView reloadData];
        }else if([_model.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}


- (void)loadUpdateRefreshWithBindingIdentity:(NSString *)BindingIdentity{
    _pageNum=@"1";
    _isRefresh=YES;
    [self messageListRequest];
}

#pragma mark -删除消息
- (void)setDeleteMessageInfoRequest{
    NSMutableArray  *empIdArr=[NSMutableArray new];
    PersonMessageModel *model=_model.dataArr[self.deleteRow];
    NSString *setOperate=nil;
    NSDictionary *dict=@{
                         @"msgId":model.ids?model.ids:@"",
                         };
    [empIdArr addObject:dict];
    if (![model.sendEmpId isEqual:[LZXHelper getSessionID]]){
        setOperate=@"1";
    }else{
        setOperate=@"2";
    }
    NSDictionary *selectDict=@{@"msgList":empIdArr,
                               @"setOperate":setOperate
                               };
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:selectDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    //[LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:setMsgInfo soapBody:soap success:^(id responseObject) {
        //[LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        BasicModel *model=[[BasicModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"220"]) {
            [self messageListRequest];
            if (self.deleteView) {
                [self.deleteView removeFromSuperview];
                self.deleteView=nil;
            }
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }else if([model.code isEqualToString:@"200"]){
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
